<?php

namespace app\middleware;

use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

/**
 * 自动记录增删改操作的日志
 */
class ActionLog implements MiddlewareInterface
{
    /**
     * 要记录的方法
     * @var string[]
     */
    public $actions= ['/delete','/add','/update'];
    public $actionNames= ['删除了记录[:id]','新增了一条记录','修改了记录[:id]'];
    public function process(Request $request, callable $next): Response{

        // 这儿只自动记录 基础的 增删改的操作
        $uri = $request->uri();
        $method = $request->method();
        // 只记录Post操作
        if($method=='POST'){
            $actName = '';
            foreach ($this->actions as $key => $act ){
                if(strpos($uri,$act)!==false){
                    $actName = str_replace(':id',$request->input('id'),$this->actionNames[$key]);
                    break;
                }
            }
            if($actName){
                tuActionLog($request,$actName,1);
            }
        }

        // 继续向下执行
        $response = $next($request);

        return $response;
    }
}